﻿//-----------------------------------------------------------------------
// <copyright file="NhSessionFactory.cs" company="OverrideThis">
//     Copyright (c) 2010 OverrideThis.com
// </copyright>
//-----------------------------------------------------------------------
namespace OverrideThis.Core.Infrastucture.Repository.Impl
{
    using FluentNHibernate;
    using FluentNHibernate.Cfg;
    using FluentNHibernate.Cfg.Db;
    using NHibernate;

    public class NhSessionFactory
    {
        private readonly INhSessionFactoryCfg cfg;
        private SessionSource sessionSource;

        public NhSessionFactory(INhSessionFactoryCfg cfg)
        {
            this.cfg = cfg;
        }

        public ISession Get()
        {
            EnsureSessionSourceCreated();
            var session = this.sessionSource.CreateSession();
            session.FlushMode = FlushMode.Commit;
            return session;
        }

        private void EnsureSessionSourceCreated()
        {
            if (this.sessionSource != null)
                return;
            var cfg = Fluently.Configure()
                .Database(this.cfg.Provider())
                .Mappings(this.cfg.Mapping())
                .ExposeConfiguration(this.cfg.ExposeConfiguration);
            this.sessionSource = new SessionSource(cfg);
        }

        public void BuildSchema()
        {
            this.EnsureSessionSourceCreated();
            this.sessionSource.BuildSchema();
        }

        public void UseInMemoryDatabase()
        {
            var cfg = Fluently.Configure()
                .Database(SQLiteConfiguration.Standard.InMemory())
                .Mappings(this.cfg.Mapping())
                .ExposeConfiguration(this.cfg.ExposeConfiguration);
            this.sessionSource = new FluentNHibernate.Testing.SingleConnectionSessionSourceForSQLiteInMemoryTesting(cfg);
        }
    }
}
